package com.huluobo.a2203parkdemo.news

import android.text.TextUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2203parkdemo.R
import com.huluobo.a2203parkdemo.databinding.ActivityAddNewsBinding
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.text.SimpleDateFormat

@AndroidEntryPoint
class AddNewsActivity : BaseActivity<ActivityAddNewsBinding, NewsViewModel>() {
    private var time = ""
    private var newsTitle = ""
    private var newsValue = ""
    private var userId = 0
    override fun initData() {
        viewModel.addNewsSuccevss.observe(this) {
            ToastUtils.showLong("添加新闻成功")
            finish()
        }
    }

    override fun initView() {
        binding.addNewsBtn.setOnClickListener {
            time = getTime()
            newsTitle = binding.addNewsTitleEt.text.toString()
            newsValue = binding.addNewsContentEt.text.toString()
            userId = SPUtils.getInstance().getInt(Const.PARAM_USER_ID)
            val map = mutableMapOf<String, Any>()
            map[Const.PARAM_NEWS_TIME] = time
            map[Const.PARAM_NEWS_TITLE] = newsTitle
            map[Const.PARAM_NEWS_VALUE] = newsValue
            map[Const.PARAM_USER_ID] = userId

            val json = Gson().toJson(map)
            val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
            if (TextUtils.isEmpty(newsTitle)) {
                ToastUtils.showLong("请输入新闻标题")
            } else if (TextUtils.isEmpty(newsValue)) {
                ToastUtils.showLong("请输入新闻内容")
            } else {
                viewModel.addNews(body)
            }
        }
    }
}